#include "Club.h"
#include "Puck.h"
#include <math.h>

using namespace irr;
using namespace core;
using namespace scene;
using namespace video;

const f32 Club::RADIUS = 7.0165f;

Club::Club(IrrlichtDevice* device, ISceneNode* table, Puck* puck, bool invertControl)
	: _puck(puck)
	, invert(invertControl)
	, speed(1.f)
{
	smgr = device->getSceneManager();
	node = smgr->addMeshSceneNode(smgr->getMesh(L"Data/Models/bita.obj"), table);

	if (node)
		node->setMaterialType(EMT_LIGHTMAP);
}

Club::~Club(void)
{
}

void Club::update(int horDir, int verDir, int deltaX, int deltaY)
{
	lastPosition = node->getPosition();

	if (horDir || verDir)
		direction = vector3df((f32)verDir, 0.f, (f32)horDir);
	else
	{
		direction = vector3df((f32)deltaY, 0.f, (f32)deltaX);
		direction *= 0.4f;				// Reduce mouse speed
	}

	// 1st player club
	if (!invert)
	{
		position = node->getPosition() + direction;

		// Vertical movement limits
		if (position.X < RADIUS)
			position.X = RADIUS;
		
		if (position.X > (Table::SIZE.X/2 - RADIUS)) 
			position.X = Table::SIZE.X/2 - RADIUS;
	}
	// 2nd player club
	else
	{
		position = node->getPosition() - direction;

		// Vertical movement limits
		if (position.X > -RADIUS)
			position.X = -RADIUS;
		
		if (position.X < (RADIUS - Table::SIZE.X/2)) 
			position.X = RADIUS - Table::SIZE.X/2;
	}

	// Horizontal movement limits
	if (position.Z > (Table::SIZE.Z/2 - RADIUS))
		position.Z = Table::SIZE.Z/2 - RADIUS;
		
	if (position.Z < (RADIUS - Table::SIZE.Z/2))
		position.Z = RADIUS - Table::SIZE.Z/2;

	node->setPosition(position);
}

bool Club::collisionWithPuck(vector3df& puckPosition, vector3df& result, f32& speed)
{
	if (position.getDistanceFrom(puckPosition) < (RADIUS + Puck::RADIUS))
	{
		result = puckPosition - position;
		speed = abs(position.getDistanceFrom(lastPosition));
		
		position = lastPosition;
		node->setPosition(position);
		return true;
	} 
	return false;
}